<template>
  <div>
    <div class="limiter">
      <div class="container-table103">
        <div class="wrap-table101">
          <div class="progress_box" style="width: 90%">
            <el-progress class="progress_line" style="width: 90%" v-show="progressShow" :text-inside="true"
              :stroke-width="22" :color="customColor" :percentage="c_percentage" status="warning"></el-progress>
          </div>
          <ossUpload v-show="!progressShow" class="upcompon" ref="upapp" :type="'2'" :module="'ipa'"
            :change="upAppChange" :progress="upAppProgress" :success="upAppSuccess" :beforeupload="upAppbeforeupload"
            :rzstatus="rzstatus" :putBigFile="toPutBigFile">
            <div>
              <el-image :src="src"></el-image>
              <el-button>立即上传</el-button>
              <div v-show="isvip == 0" class="el-upload__text">
                点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA或.APK文件，单个文件最大支持{{
                  uploadInfo.singlesize
                }}M）
              </div>
              <div v-show="isvip == 1" class="el-upload__text">
                点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA文件，单个文件最大支持
                {{uploadInfo.singlesize}}M）
              </div>
            </div>
          </ossUpload>
        </div>
      </div>
    </div>
    <div class="upimgbox">
      <div class="upimg">
        <ossUpload v-show="!progressShow" class="upcompon" ref="upimg" :type="'1'" :module="'realname'"
          :success="upImgSuccess">
          <div>上传图片</div>
        </ossUpload>
      </div>
    </div>
  </div>
</template>

<script>
  import JsZip, {
    file,
    files
  } from "jszip";
  import ossUpload from "../common/OSSUpload";
  // import cosUpload from "../common/COSUpload";
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
      ossUpload,
      // cosUpload,
    },
    data() {
      //这里存放数据
      return {
        isGoDown: true,
        uploadFileUrl: "",
        uploadInfo: {}, //用户的信息
        src: "../../../static/上传应用按钮.png",
        headers: {},
        c_percentage: 0, //初始进度0
        progressShow: false, //最开始隐藏进度条
        new_zip: [],
        autoUpload: false,
        show_file_list: false,
        reader_c: "", //当前解压zip实体
        appName: "", //APP名称
        version: "", //版本
        Identifier: "", //包名
        zxlogo: "", //APP图标地址
        sext: "", //文件格式
        upName: "", //上传地址文件名称
        DownLink: "", //下载地址
        AppSize: 0, //APP包大小
        sjid: 0, //升级ID，0为新上传
        // isvip: 0, //是否为超级签名
        customColor: "#ff7226", //进度条颜色
        rzstatus: "1", //是否实名制
        isStop: 0,
      };
    },
    props: ["isvip"],
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      // 获取app类型，判断typeof和module传什么值

      // 获取用户信息-----这里逻辑ok
      uploadsInfo() {
        var params = new URLSearchParams();
        this.$post(this.API.Application_uploadsInfo, params).then((res) => {
          if (res) {
            console.log(res);
            this.uploadInfo = res.data.result;
            // this.rzstatus = this.uploadInfo["rzstatus"];
          }
        });
      },
      //上传文件之前的钩子,文件选取时，判断逻辑
      upAppbeforeupload(file) {
        console.log(file);
        this.sext = file.name.split(".")[file.name.split(".").length - 1];
        if (this.sext != "ipa") {
          this.$message.error("只允许上传ipa格式文件");
          return false;
        }
        if (this.isStop == 1) {
          console.log(file.status, new Date());
        }
        console.log(file);
        this.upName = file.name;
        const isLt2M = file.size / 1024 / 1024 < this.uploadInfo.singlesize;
        if (
          parseInt(this.uploadInfo.allowsize) <
          parseInt(file.size / 1024 / 1024) +
          parseInt(this.uploadInfo.uploadedsize)
        ) {
          this.$message.error(
            "上传空间，已超出限定大小:" + this.uploadInfo.allowsize + "M"
          );
          // this.$refs.upapp.clearFiles();
          return false;
        }

        if (!isLt2M) {
          this.$message.error(
            "上传文件大小不能超过 " + this.uploadInfo.singlesize + "MB!"
          );
          return false;
        }
        console.log(file);
        // let that = this;
        const AppInfoParser = require("app-info-parser");
        const parser = new AppInfoParser(file.raw); // or xxx.ipa
        parser
          .parse()
          .then((result) => {
            if (this.isStop == 1) {
              console.log("app info ----> ", result);
            }
            var icon = "";
            var appName = "";
            var hpackageName = "";
            var hversion = "";
            var MinimumOSVersion = "";
            console.log(this.sext);
            console.log(result);
            if (this.sext == "apk") {
              appName = result.application.label[0];
              icon = result.icon;
              hpackageName = result.package;
              hversion = result.versionName;
              MinimumOSVersion = result.compileSdkVersion;
            } else if (this.sext == "ipa") {
              appName = result.CFBundleDisplayName;
              icon = result.icon;
              hpackageName = result.CFBundleIdentifier;
              hversion = result.CFBundleShortVersionString;
              MinimumOSVersion = result.MinimumOSVersion;
            }

            this.appName = appName;
            this.newzxlogo = icon;
            this.Identifier = hpackageName;
            this.version = hversion;
            //显示进度条
            this.progressShow = true;
            console.log("上传前验证完成");
            if (file.size / 1024 / 1024 >= 200) {
              this.toPutBigFile(file);
            }
          })
          .catch((err) => {
            console.log("err ----> ", err);
            this.$message.error(err);
            this.isGoDown = false;
            return this.isGoDown;
          });
        if (file.size / 1024 / 1024 <= 200) {
          return this.isGoDown;
        }
      },
      // 上传超过200M的文件
      toPutBigFile(file) {
        console.log(`上传大型的文件`);
        this.uploadFileUrl = this.uploadInfo.fileUploadUrl;
        console.log(this.uploadFileUrl);
        this.upAppChange(file);
      },
      // 上传状态发生改变时
      upAppChange(res) {
        console.log(res + "先上传文件");
        // 该app的大小
        this.AppSize = res.size;
        if (res.size / 1024 / 1024 >= 200) {
          var params = new FormData();
          params.append("file", res.raw);
          console.log(this.uploadFileUrl);
          const config = {
            onUploadProgress: this.upAppProgress,
          };
          this.$post(this.uploadFileUrl, params, config).then((res) => {
            console.log(res);
            this.upAppSuccess(res.path);
          });
        }
      },
      // 上传成功调用
      upAppSuccess(url) {
        console.log(url + "获取文件下载的链接");
        this.DownLink = url;
        if (this.newzxlogo) {
          this.base64ToFile(this.newzxlogo);
        } else {
          this.zxlogo = this.newzxlogo;
          this.submitData();
        }
      },
      base64ToFile(data) {
        // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
        let binary = atob(data.split(",")[1]);
        let mime = data.split(",")[0].match(/:(.*?);/)[1];
        let array = [];
        for (let i = 0; i < binary.length; i++) {
          array.push(binary.charCodeAt(i));
        }
        let fileData = new Blob([new Uint8Array(array)], {
          type: mime,
        });

        let file = new File([fileData], `${new Date().getTime()}.png`, {
          type: mime,
        });
        console.log(file);
        this.$refs.upimg.postImage(file);
      },
      upImgSuccess(url) {
        console.log(url);
        this.zxlogo = url;
        this.$nextTick(function () {
          this.submitData();
        });
      },
      // 文件上传时的钩子
      upAppProgress(res) {
        console.log(res);
        this.c_percentage = Math.floor((res.loaded / res.total) * 100);
        console.log(this.c_percentage);
      },
      submitData() {
        var params = new URLSearchParams();
        params.append("DownLink", this.DownLink); //下载地址
        params.append("hext", this.sext); //文件格式
        params.append("zxlogo", this.zxlogo); //APP图标地址
        params.append("happName", this.appName); //APP名称
        params.append("iAppSize", this.AppSize); //APP包大小
        params.append("hpackageName", this.Identifier); //包名
        params.append("hversion", this.version); //版本
        params.append("isvip", this.isvip);
        params.append("sjid", this.sjid); //升级ID，0为新上传
        params.append("apkName", this.upName); //上传地址文件名称
        console.log(params);
        if (this.isStop == 1) {
          console.log(params, "开始提交数据:" + new Date());
        }
        this.$post(this.API.Appupload_uploadData, params).then((res) => {
          if (res) {
            console.log(res);
            if (this.isStop == 1) {
              console.log(res, "提交数据成功:" + new Date());
            }
            sessionStorage.setItem("setMenuIndex_application", 1);
            sessionStorage.setItem("setMenuIndex_supuer", 1);
            if (this.isStop == 1) {
              console.log("跳转成功:" + new Date());
              return;
            }
            if (this.DownLink) {
              this.$confirm("app正在审核中，请前往应用列表查看", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                .then(() => {
                  location.reload();
                })
                .catch(() => {
                  this.$message({
                    type: "warning",
                    message: "app正在审核中，请前往应用列表查看",
                  });
                });
            }
          }
        });
      },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      var Authorization = sessionStorage["token"];
      this.headers = {
        Authorization: Authorization
      };
      var appID = this.$route.query.appID;
      if (appID > 0) {
        this.sjid = appID;
      }
      this.uploadsInfo();

      this.isStop = this.$route.query.isStop;
      console.log("appID:" + this.sjid);
      console.log("isvip:" + this.isvip);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
  };

</script>
<style scoped>
  .progress_box {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  div>>>.el-button--default {
    border: none;
  }

  .content {
    margin: 30px 0px 30px 0px;
    background: #ffffff;
    box-shadow: 0px 4px 10px 2px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
  }

  .limiter {
    width: 100%;
    margin: 0 auto;
  }

  .container-table103 {
    width: 100%;
    min-height: 100vh;
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
  }

  .container-table102 {
    width: 100%;
    min-height: 100vh;
    border-radius: 4px 0px 0px 4px;
  }

  .wrap-table101 {
    width: 100%;
    max-width: 1170px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .upcompon {
    width: 210px;
    height: auto;
    margin: 0 auto;
    background-color: rgba(30, 30, 30, 0.8);
  }

  .upcompon>>>.el-upload-dragger {
    background-color: rgba(30, 30, 30, 0.8);
  }

  .upcompon .el-upload-dragger .el-upload__text {
    color: #fff;
  }

  div>>>.avatar-uploader .el-upload {
    border: none !important;
  }

  div>>>.el-upload__input {
    display: none;
  }

  div>>>.el-upload-dragger {
    border: none;
  }

  .el-button {
    width: 210px;
    /* height: 50px; */
    background-image: linear-gradient(to right, #eb9231, #eb5431);
    font-size: 16px;
    color: #fff;
    border-radius: 30px;
  }

  div>>>.el-button span {
    margin-left: 40px;
  }

  .el-image {
    position: absolute;
    margin-top: 12px;
    margin-left: 45px;
  }

  .el-upload__text {
    color: #adadad;
    font-size: 12px;
    /* width: 204px; */
    /* margin-left: 80px; */
    margin-top: 10px;
  }

  div>>>.el-upload-dragger {
    width: 210px;
    /* height: 50px; */
  }

  div>>>.upload-demo {
    width: 180px;
    /* height: 50px; */
    position: absolute;
    top: 40%;
  }

  .upimgbox {
    width: 100%;
    height: auto;
    position: relative;
  }

  .upimg {
    position: absolute;
    left: -999999999px;
  }

  /* 媒体查询 */
  @media (max-width: 992px) {
    .container-table103 {
      min-height: 70vh;
    }
  }

  @media (max-width: 576px) {}

  .message {
    width: 350px;
    height: 239px;
    background: linear-gradient(180deg, #ffffff 0%, #ffffff 40%, #ffffff 100%);
    /* background-color: aqua; */
    opacity: 1;
    border-radius: 5px;
    font-family: SimHei;
    text-align: center;
  }

  .message-info-image {
    width: 100%;
  }

  .message-info-ok {
    margin-top: 10px;
    height: 13px;
    font-size: 13px;
    font-weight: 600;
    line-height: 0px;
    color: #2d2d2d;
    letter-spacing: 1px;
    opacity: 1;
  }

  .message-info-title {
    margin-top: 15px;
    height: 11px;
    font-size: 12px;
    font-weight: 400;
    line-height: 0px;
    color: #2d2d2d;
    letter-spacing: 1px;
    opacity: 1;
  }

  .message-submit {
    margin-top: 25px;
    font-size: 8px;
  }

  .message-cancel {
    float: left;
    margin-left: 15%;
    width: 100px;
    height: 28px;
    background: linear-gradient(135deg, #ff9b64 0%, #ff752a 100%);
    opacity: 0.22;
    border-radius: 1px;
    color: #2d2d2d;
    padding: auto;
    text-align: center;
    line-height: 28px;
    cursor: pointer;
  }

  .message-ok {
    float: left;
    margin-left: 10%;
    width: 100px;
    height: 28px;
    background: linear-gradient(135deg, #ff9b64 0%, #ff752a 100%);
    opacity: 1;
    border-radius: 1px;
    color: #ffffff;
    padding: auto;
    text-align: center;
    line-height: 28px;
    cursor: pointer;
  }

</style>
